package servlets.adsServlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.JsonManager;
import structures.FeedbackInsertionOutcome;

public class LeaveFeedbackServlet extends HttpServlet {
	
	private static final long serialVersionUID = 7933778591371369780L;
	private static final String INSERTFEEDBACKURLBASE = "http://localhost:8080/ISellToYouRESTWebService/InsertFeedback?";
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		String idSeller,answer, idAdvertisement, feedbackText, feedbackValue, inputLine;
		URL url;
		BufferedReader reader;
		StringBuffer responseBuffer;
		JsonManager jsonManager;
		FeedbackInsertionOutcome feedbackInsertionOutcome;
		jsonManager = new JsonManager();
		idSeller = request.getParameter("idSeller");
		idAdvertisement = request.getParameter("idAdvertisement");
		feedbackText = request.getParameter("Text").replace(" ", "%20");
		feedbackValue = request.getParameter("Value");
		
		try {
			
			url = new URL(INSERTFEEDBACKURLBASE + "idSeller=" + idSeller + "&idAdvertisement=" + idAdvertisement + "&feedbackText=" + feedbackText + "&feedbackValue=" + feedbackValue);
			HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
			httpConnection.setRequestMethod("PUT");
			httpConnection.setDoOutput(true); 
			httpConnection.setDoInput(true);
			httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			
			reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));

			responseBuffer = new StringBuffer();
			
			while ((inputLine = reader.readLine()) != null) {
				responseBuffer.append(inputLine);
			}
			reader.close();

			answer = responseBuffer.toString();

			if(answer.equals("null"))
				throw new Exception();
			
			feedbackInsertionOutcome = jsonManager.toFeedbackInsertionOutcome(answer);
			request.getSession().setAttribute("advertisement", feedbackInsertionOutcome.getAdvertisement());
			request.getSession().setAttribute("feedback", Boolean.toString(feedbackInsertionOutcome.isError()));
			request.getSession().setAttribute("gamifyErrors", Boolean.toString(feedbackInsertionOutcome.isGamifyErrors()));
			try {
				response.sendRedirect(request.getContextPath() + "/advertisement.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			try {
				response.sendRedirect(request.getContextPath() + "/advertisement.jsp");
				request.getSession().setAttribute("feedback", "false");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
